import { FolderApi, FileApi } from '@/api/infra/file'
import { cloneDeep } from 'lodash-es'
import { folderListToTree, mergeFolderSourceData, treeData, getTreeNodeParents, getActiveData, returnSize } from '../utils/index'
import useSourceConfig from './useSourceConfig'
const usePublic = treeRef => {
  const { success } = useMessage()
  // 资源库上传相关参数
  const { getSourceConfig } = useSourceConfig()

  const initInfo: any = ref({
    isRecycle: false, // true: 回收站； false: 资源库
    isCard: true, // true: 卡片布局； false: 表格布局
    isOldCard: true, // 回收站只有表格布局，切换到回收站时，需将资源库的布局类型保存下来，该字段主要实现切换回资源库时，保留其原始布局类型
    breadcrumbList: [], // 资源路径数据
    folderName: '', // 文件夹通过名称过滤查询字段
    folderList: [], // 文件夹数据
    defaultExpandNodes: [], // 文件夹树结构默认展开节点的id集合
    isContextmenuClick: false, // 当前是否点击了右键菜单中的某一个菜单
    rightClickFolder: null, // 右键点击文件夹树结构时，获取当前点击的节点数据
    isUploadDialogShow: false, // 上传文件弹窗是否显示，用来在新建文件夹时，是否需要通知上传文件弹窗，文件夹已更改
    form: {
      // 资源查询相关参数字段
      search: '', // 资源名称
      type: '', // 资源类型
      folder_id: 0 // 资源所属文件夹id
    },
    sourceList: [], // 资源数据
    fileTypeList: [
      { label: '图片', value: 'image', disabled: false },
      { label: '视频', value: 'mp4', disabled: false },
      { label: '音频', value: 'mp3', disabled: false },
      { label: '文件', value: 'file', disabled: false }
    ],
    titleInputRefs: [], // 行内编辑资源名称时，获取input框DOM对象
    selectedInfo: {
      // 资源进行选择时用到的参数字段
      checkedTitle: '全选', // 全选文字变量
      isIndeterminate: false, // 半选状态
      allChecked: false, // 全选状态
      isUsedChecked: false, // 是否有已引用的资源被选中
      folderCount: 0, // 已选中的文件夹数量
      sourceCount: 0, // 已选中的资源数量
      usedCheckedCount: 0, // 已选中的已引用的资源数量
      activeSingleSource: null // 已选中单个资源时，记录该资源，如选择多个了，不再记录
    },
    uploadConfig: {
      // 上传资源需要传递的相关参数字段
      multiple: true, // 是否可多选
      type: 'all', // 上传类型  取值：all|image|video|file
      isAllowChangeType: true, // 是否允许在上传文件弹窗中切换上传资源类型
      maxNumber: 0,
      accept: {
        image: '',
        video: '',
        file: ''
      },
      maxSize: {
        image: 0,
        video: 0,
        file: 0
      },
      fileSize: {
        image: '',
        video: '',
        file: ''
      }
    },
    recycleInfo: {
      total: 0,
      form: {
        page: 1,
        limit: 20,
        search: ''
      },
      returnDelete: {
        ids: '',
        type: 0
      }
    },
    isChooseResource: false,
    isMultiple: false,
    fileTypeArr: ['7z', 'ai', 'cdr', 'class', 'css', 'csv', 'doc', 'dockerfile', 'docx', 'exe', 'gitignore', 'html', 'iso', 'jar', 'java', 'js', 'json', 'md', 'pdf', 'ppt', 'pptx', 'pr', 'psd', 'py', 'rar', 'sql', 'svg', 'txt', 'xls', 'xlsx', 'xml', 'yml', 'zip'],
    newUploadList: [],
    popShow: false
  })

  // 获取文件夹数据
  const getFolderList = () => {
    FolderApi.list({ search: '' }).then((res: any) => {
      console.log(res)
      if (res.code === 200) {
        const rootFolder = [
          {
            id: 0,
            folder_id: '',
            title: '全部',
            isFolder: true,
            level: 1,
            isTitleEdit: false,
            active: true,
            children: []
          }
        ]
        rootFolder[0].children = folderListToTree(res.data)
        treeData(rootFolder, false, [])
        initInfo.value.folderList = rootFolder
        const newFolder: any = getActiveData(initInfo.value.folderList, initInfo.value.form.folder_id)
        treeRef.value.setCheckedKeys([newFolder.id], false)
        initInfo.value.breadcrumbList = getTreeNodeParents(cloneDeep(initInfo.value.folderList), newFolder)
        initInfo.value.breadcrumbList.push(newFolder)
        initInfo.value.defaultExpandNodes = []
        initInfo.value.breadcrumbList.forEach(item => {
          initInfo.value.defaultExpandNodes.push(item.id)
        })
        getSourceList()
      }
    })
  }

  // 获取资源数据
  const getSourceList = () => {
    FileApi.list(initInfo.value.form).then((res: any) => {
      if (res.code === 200) {
        let checked = []
        // 有在弹窗中上传的内容
        console.log(initInfo.value.popShow)
        if (initInfo.value.popShow) {
          checked = initInfo.value.newUploadList
        } else {
          checked = []
        }
        initInfo.value.sourceList = mergeFolderSourceData(cloneDeep(initInfo.value.folderList), res.data, initInfo.value.form.folder_id, checked, initInfo.value.isMultiple)
        console.log(initInfo.value.sourceList)
        initInfo.value.newUploadList = []
      }
    })
  }

  // 初始化资源选中相关数据参数的初始值
  const resetSelectedInfo = () => {
    initInfo.value.selectedInfo.checkedTitle = '全选'
    initInfo.value.selectedInfo.isIndeterminate = false
    initInfo.value.selectedInfo.allChecked = false
    initInfo.value.selectedInfo.isUsedChecked = false
    initInfo.value.selectedInfo.folderCount = 0
    initInfo.value.selectedInfo.sourceCount = 0
    initInfo.value.selectedInfo.usedCheckedCount = 0
    initInfo.value.selectedInfo.activeSingleSource = null
  }

  // 初始化重新获取页面所有数据
  const initFolder = () => {
    console.log(initInfo.value.form.folder_id, '当前文件夹ID222')
    initInfo.value.rightClickFolder = null
    if (initInfo.value.isRecycle) {
      initInfo.value.isRecycle = false
      initInfo.value.isCard = initInfo.value.isOldCard
    }
    resetSelectedInfo()
    getFolderList()
  }

  // 布局类型切换事件
  const cardListChangeHandler = v => {
    if (!initInfo.value.isRecycle) {
      initInfo.value.isCard = v
    }
  }

  // 设置资源上传参数
  const setUploadParams = () => {
    const res = getSourceConfig()
    const config: any = {}
    Promise.all([res]).then((data: any) => {
      data[0].forEach((item: any) => {
        config[item.key] = item.value
      })
      initInfo.value.uploadConfig.accept.image = config.image_exts
      initInfo.value.uploadConfig.accept.video = config.video_exts
      initInfo.value.uploadConfig.accept.file = config.file_exts
      initInfo.value.uploadConfig.maxSize.image = parseInt(config.image_size)
      initInfo.value.uploadConfig.maxSize.video = parseInt(config.video_size)
      initInfo.value.uploadConfig.maxSize.file = parseInt(config.file_size)
      initInfo.value.uploadConfig.fileSize.image = returnSize(config.image_size)
      initInfo.value.uploadConfig.fileSize.video = returnSize(config.video_size)
      initInfo.value.uploadConfig.fileSize.file = returnSize(config.file_size)
    })
  }

  // 检测引用情况
  const checkUseCondition = () => {
    const checkedIds: any = []
    initInfo.value.sourceList.forEach(item => {
      if (item.active) {
        checkedIds.push(item.id)
      }
    })
    const result = {
      ids: checkedIds.join(',')
    }
    FileApi.check(result).then((res: any) => {
      if (res.code === 200) {
        success(res.msg)
        initFolder()
      }
    })
  }

  // 是否弹窗
  const changePopShowStatus = show => {
    console.log(show, 'popshoustatus')
    initInfo.value.popShow = show
  }

  return {
    initInfo,
    getFolderList,
    getSourceList,
    initFolder,
    resetSelectedInfo,
    cardListChangeHandler,
    setUploadParams,
    checkUseCondition,
    changePopShowStatus
  }
}
export default usePublic
